package com.hfi.restful.web.handler;

import com.hfi.restful.exception.ErrorCode;
import com.hfi.restful.exception.MyException;
import com.hfi.restful.response.Response;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 全局异常处理类
 * @author ChangLiang
 * @date 2019/7/30
 */
@RestControllerAdvice
public class ControllerExceptionHandler {

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Response handleConstraintViolationExceptions(ConstraintViolationException ex) {
        Map<String, String> validMessages = new HashMap<>(10);
        Iterator<ConstraintViolation<?>> iterator = ex.getConstraintViolations().iterator();
        while (iterator.hasNext()) {
            ConstraintViolation<?> next = iterator.next();
            validMessages.put(next.getPropertyPath().toString(), next.getMessageTemplate());
        }
        return getResponse(validMessages, ErrorCode.PARAM_VALIDATION_FAIL);
    }

    private Response getResponse(Map<String, String> validMessages, ErrorCode errorCode) {
        Response response = new Response();
        response.setErrorcode(errorCode.value);
        response.setValue(errorCode.memo);
        response.setData(validMessages);
        return response;
    }


    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Response handleValidationExceptions(MethodArgumentNotValidException ex) {
        // hashmap 初始容量为16
        Map<String, String> validMessages = new HashMap<>(10);
        ex.getBindingResult().getAllErrors().stream().forEach(
                error -> {
                    FieldError fieldError = (FieldError) error;
                    validMessages.put(fieldError.getField(),error.getDefaultMessage());
                }
        );
        return getResponse(validMessages, ErrorCode.PARAM_VALIDATION_FAIL);
    }

    @ExceptionHandler(MyException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Response handleMyException(MyException ex) {
        return getResponse(ex.getValidMessages(), ex.getErrorCode());
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(code= HttpStatus.INTERNAL_SERVER_ERROR)
    public Response resolveException(Exception ex) {
        ex.printStackTrace();
        Response response = new Response();
        response.setErrorcode("500");
        response.setValue("服务器出错啦");
        return response;
    }
}
